package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * description: 工信门户小蓝本请求工具
 * auth fcb
 * date 2025-06-10 18:21
 **/
@Service
@Slf4j
public class GxmhXLBHttpRequestService {

    private static final String GXMH_XLB_URL = "https://openapi.xiaolanben.com/api/";

    private static final String accessId = "e@c9d0fb7f2a3x";

    private static final String accessToken= "jEdKBnv4Lp3BJ7tQYbAQy0MenZzrICaByqjWUGtq0T0QzwMlqBNmcCc38R47bmLx";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 请求小蓝本接口GET方式
     * @param interfaceCode 接口编号
     * @param paramMap 参数
     * @return
     */
    public Message requestGet(String interfaceCode, Map<String, String> paramMap) {
        String url = GXMH_XLB_URL + interfaceCode + this.buildQueryString(paramMap);
        try {
            HttpHeaders httpHeaders = this.buildCommonHeaders();
            HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            if(!responseEntity.getStatusCode().is2xxSuccessful()) {
                log.error("【请求工信小蓝本接口】请求失败, 接口编号：{}  http status :{}", interfaceCode, responseEntity.getStatusCode());
                return Message.fail();
            }
            String body = responseEntity.getBody();
            //log.info("【请求工信小蓝本接口】返回： {}", body);
            if(StrUtil.isEmpty(body)) {
                return Message.success("");
            }
            if(body.startsWith("[")) {
                JSONArray array = JSON.parseArray(body);
                return Message.success(array);
            }
            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject.containsKey("code") ) {
                return Message.fail(jsonObject.getString("message"));
            }
            return Message.success(jsonObject);
        }catch (Exception e) {
            log.error("【请求工信小蓝本接口异常】:{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail();
        }
    }

    public Message requestPost(String interfaceCode, String jsonStr) {
        String url = GXMH_XLB_URL + interfaceCode;
        try {
            HttpHeaders httpHeaders = this.buildCommonHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(jsonStr, httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            if(!responseEntity.getStatusCode().is2xxSuccessful()) {
                log.error("【请求工信小蓝本接口】请求失败, 接口编号：{}， http status :{}", interfaceCode, responseEntity.getStatusCode());
                return Message.fail();
            }
            String body = responseEntity.getBody();
            //log.info("【请求工信小蓝本接口】返回： {}", body);
            if(StrUtil.isEmpty(body)) {
                return Message.success("");
            }
            if(body.startsWith("[")) {
                JSONArray array = JSON.parseArray(body);
                return Message.success(array);
            }
            JSONObject jsonObject = JSON.parseObject(body);
            if(jsonObject.containsKey("code") ) {
                return Message.fail(jsonObject.getString("message"));
            }
            return Message.success(jsonObject);
        }catch (Exception e) {
            log.error("【请求工信小蓝本接口异常】:{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail();
        }
    }

    // 查询接口的数据总数
    public Integer requestTotalCount(String interfaceCode, Map<String, String> map, String httpType, String keyWrapper, String totalWrapper){
        Message message = null;
        if("get".equals(httpType)) {
            message = this.requestGet(interfaceCode, map);
        }else if("post".equals(httpType)) {
            message = this.requestPost(interfaceCode, JSONUtil.toJsonStr(map));
        }else {
            throw new BusinessException("不支持的请求类型：" + httpType);
        }
        if(!MessageCodeConstant.MSG_SUCCESS_CODE.equals(message.getCode())) {
            throw new BusinessException("请求数据失败");
        }
        Object obj = message.getObj();
        if(obj instanceof JSONArray) {
            throw new BusinessException("请求的数据暂无法获取分页");
        }else if(obj instanceof JSONObject) {
            Integer totalCount = this.getInteger(keyWrapper, totalWrapper, (JSONObject) obj);
            return totalCount;
        }else {
            throw new BusinessException("暂不支持的数据分页");
        }
    }

    private Integer getInteger(String keyWrapper, String totalWrapper, JSONObject obj) {
        JSONObject wrapperData = obj.getJSONObject(keyWrapper);
        if(wrapperData == null) {
            throw new BusinessException("处理分页时未获取到指定的数据对象：" + keyWrapper);
        }
        JSONObject totalData = wrapperData.getJSONObject(totalWrapper);
        if(totalData == null) {
            throw new BusinessException("处理分页时未获取到指定的数据对象：" + totalWrapper);
        }
        Integer totalCount = totalData.getInteger("totalCount");
        if(totalCount == null) {
            throw new BusinessException("处理分页时未获取到指定的数据对象：" + totalWrapper + "下的totalCount");
        }
        return totalCount;
    }

    private String buildQueryString(Map<String, String> paramMap) {
        if(CollectionUtil.isEmpty(paramMap)) {
            return "";
        }
        StringBuilder queryString = new StringBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            queryString.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return "?" + queryString.substring(0, queryString.length() - 1);
    }

    private HttpHeaders buildCommonHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("accessId", accessId);
        headers.add("accessToken", accessToken);
        return headers;
    }
}
